import 'dart:math';
import 'dart:ui';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';

import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/entity/home/video_list_entity.dart';
import 'package:qianyi/state/token.dart';

import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/home/alumb_vo_list.dart';
import '../../../../entity/home/trendVo.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_manager.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../view_model/mine/album_view_model.dart';
import '../../../../view_model/mine/trend_view_user_model.dart';


class AlbumViewMine extends StatefulWidget {
  const AlbumViewMine({Key? key}) : super(key: key);

  @override
  _albumViewState createState() => _albumViewState();
}

class _albumViewState extends State<AlbumViewMine> with AutomaticKeepAliveClientMixin<AlbumViewMine> ,SingleTickerProviderStateMixin{
  TokenController tokenController = Get.find();
  HomeTabController homeTabController = Get.find();
  @override
  Widget build(BuildContext context) {
    super.build(context); // 重要：调用super.build(context)以保持状态
    return ChangeNotifierProvider(
        create: (BuildContext context) => AlbumViewModel(),
        child: Consumer<AlbumViewModel>(
            builder: (context, viewModel, child) {
              ;
              return CustomRefresh(


                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,
                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child: SingleChildScrollView(
                      child:  Column(
                        children: [
                          MaterialButton(

                            //背景颜色
                            // color: WcaoTheme.primary,
                            //边框样式
                            shape: const RoundedRectangleBorder(
                              //边框颜色
                              side: BorderSide(
                                color: Color(0xffe4e4e4),
                                width: 1,
                              ),
                              //边框圆角
                              borderRadius: BorderRadius.all(
                                Radius.circular(13),
                              ),
                            ),
                            //按钮高度
                            height: 32,
                            //按钮最小宽度
                            minWidth: 60,
                            //点击事件
                            onPressed: () {
                              Get.toNamed("/mine/dongtai/addAlbumViewMine");
                            },
                            child: const Text(
                              "+ 创建专辑",
                              style: TextStyle(fontSize: 12),
                            ),
                          ),

                          MasonryGridView.count(
                            padding: EdgeInsets.all(2),
                            // 展示几列
                            crossAxisCount: 2,
                            mainAxisSpacing: 4, // 纵向间距
                            crossAxisSpacing: 4, // 横向间距

                            // 元素总个数
                            itemCount: viewModel.datas.length,
                            // 单个子元素
                            itemBuilder: (BuildContext context, int index) {
                              AlbumVo album = viewModel.datas[index];

                              return GestureDetector(
                                onTap: () {
                                  homeTabController.albumDetailId = album.id!;
                                  Get.toNamed("/mine/albumScreen");
                                },
                                child:  Column(
                                  children: [
                                    FancyShimmerImage(
                                      height: getRandomHeight(),
                                      imageUrl: album.cover!,
                                      boxFit: BoxFit.cover,errorWidget:Image(
                                      image: AssetImage("assets/icon/Snipaste_2024-11-19_08-53-03.jpg"),
                                      fit: BoxFit.cover, // 根据需要选择 BoxFit
                                    ),)
                                    ,Text('${album.name}',style: TextStyle(
                                        fontWeight: FontWeight.w400
                                    ),),

                                    Text("${album.imgCount}张图片 | ${album.collectionCount}人收藏")


                                  ],
                                ),
                              );;
                            },


                            //本身不滚动，让外面的singlescrollview来滚动
                            physics:const NeverScrollableScrollPhysics(),
                            shrinkWrap: true, //收缩，让元素宽度自适应
                          ),
                        ],
                      )
                  )


              );
            })
    );


  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

double getRandomHeight() {
  // 生成一个随机高度
  double height = Random().nextDouble() * (230 - 80) + 138;
  return   height ;
}
buildWateFall(TrendViewUserModel viewModel) {
  TokenController tokenController = Get.find();

  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
  return MasonryGridView.count(
    padding: EdgeInsets.all(2),
    // 展示几列
    crossAxisCount: 2,
    // 元素总个数
    itemCount: viewModel.datas.length,
    // 单个子元素
    itemBuilder: (BuildContext context, int index) {
      TrendEntity trendEntity = viewModel.datas[index];
      // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
      return GestureDetector(
        onTap: () async {

          String uid = await tokenController.getUid();
          Map<String,dynamic> params = {
            "mid":trendEntity.mid,
            "uid": uid
          };
          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
          imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
          await imageDetailVideoController.getImageVideoDetail();
          Get.toNamed("/ui/home/imageVideoDetail");

        },
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.0),
          child:  Column(
            children: [
              FancyShimmerImage(
                height: getRandomHeight(),
                imageUrl: trendEntity.cover!,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [

                  Flexible(

                    child: Text(
                      trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                      overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                    ),

                  ),
                  Row(
                    children: [
                      Icon(
                        CupertinoIcons.heart,size: 14,
                        color: Colors.grey,),
                      Text(trendEntity.agreeCount as String)
                    ],
                  )



                ],
              )

              ,


            ],
          ),
        ),
      );
    },

    // 纵向元素间距
    mainAxisSpacing: 5,
    // 横向元素间距
    crossAxisSpacing: 5,
    //本身不滚动，让外面的singlescrollview来滚动
    physics:const NeverScrollableScrollPhysics(),
    shrinkWrap: true, //收缩，让元素宽度自适应
  )


      ;


}
